package com.zzyl.service.impl;

import cn.hutool.core.util.StrUtil;
import com.zzyl.constant.Constants;
import com.zzyl.dto.UserLoginRequestDto;
import com.zzyl.entity.Member;
import com.zzyl.mapper.MemberMapper;
import com.zzyl.properties.JwtTokenManagerProperties;
import com.zzyl.service.MemberService;
import com.zzyl.service.WechatService;
import com.zzyl.utils.JwtUtil;
import com.zzyl.utils.StringUtils;
import com.zzyl.vo.LoginVo;

import org.assertj.core.util.Lists;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

@Service
public class MemberServiceImpl implements MemberService {

    @Autowired
    private WechatService wechatService;
    @Autowired
    private MemberMapper memberMapper;
    @Autowired
    private JwtTokenManagerProperties jwtTokenManagerProperties;
    static ArrayList DEFAULT_NICKNAME_PREFIX = Lists.newArrayList(
            "生活更美好",
            "大桔大利",
            "日富一日",
            "好柿开花",
            "柿柿如意",
            "一椰暴富",
            "大柚所为",
            "杨梅吐气",
            "天生荔枝"
    );



    /**
     * 小程序登录逻辑
     * @param userLoginRequestDto
     * @return
     */
    @Override
    public LoginVo login(UserLoginRequestDto userLoginRequestDto) {
        //1.获取openid
        String openid = wechatService.getOpenid(userLoginRequestDto.getCode());
        //2.根据openid查询用户
        Member menber = memberMapper.getByOpenId(openid);
        //3.如果用户为空，新增用户
        if (menber == null) {
            //新增用户
            menber = Member.builder().openId(openid).build();
        }
        //4.调用微信api获取手机号
        String phone = wechatService.getPhone(userLoginRequestDto.getPhoneCode());
        //5.保存或修改用户
        saveOrUpdate(menber, phone);
        //6.返回token
        Map<String,Object> claims = new HashMap<>();
        claims.put(Constants.JWT_USERID,menber.getId());
        claims.put(Constants.JWT_USERNAME,menber.getName());
        String token = JwtUtil.createJWT(jwtTokenManagerProperties.getBase64EncodedSecretKey(), jwtTokenManagerProperties.getTtl(), claims);
        LoginVo loginVo = new LoginVo();
        loginVo.setToken(token);
        loginVo.setNickName(menber.getName());
        return loginVo;
    }

    /**
     * 保存或修改用户
     * @param member
     * @param phone
     */
    private void saveOrUpdate(Member member, String phone) {
        //判断手机号是否一致
        if(!phone.equals(member.getPhone())){
            member.setPhone(phone);
        }
        //判断是否存在数据库自增id
        if(member.getId() != null){
            memberMapper.update(member);
            return;
        }
        member.setName(DEFAULT_NICKNAME_PREFIX.get((int)(Math.random() * DEFAULT_NICKNAME_PREFIX.size()))+ StringUtils.substring(phone,7));
        memberMapper.save(member);
    }
}
